﻿using System;
using System.Globalization;
using System.IO;
using BSDS.Core.Infrastructure.Logging;
using BSDS.Core.Model.Services.Jobs;

namespace BSDS.Core.Data.Local.Jobs
{
    public class DownloadJobSerializer
    {
        private readonly Logger logger;

        public DownloadJobSerializer(Logger logger)
        {
            this.logger = logger;
        }

        public void Serialize(DownloadJob job, string filename)
        {
            logger.Log("Saving job information to file: " + filename);

            using (var writer = new StreamWriter(filename))
            {
                writer.WriteLine(job.Id);
                writer.WriteLine(job.SubmissionDate.ToString(CultureInfo.InvariantCulture));
                writer.WriteLine(job.DataSourceName);
                writer.WriteLine(job.RecordsNumber);
                writer.WriteLine(job.Command);
                writer.WriteLine(job.OutFile);
                writer.WriteLine(job.Format.Value);
                writer.WriteLine(job.Portal);
                writer.WriteLine(job.Link);
            }
        }

        public DownloadJob Deserialize(string filename)
        {
            using (var reader = new StreamReader(filename))
            {
                return new DownloadJob
                {
                    Id = reader.ReadLine(),
                    SubmissionDate = DateTime.Parse(reader.ReadLine(), CultureInfo.InvariantCulture),
                    DataSourceName = reader.ReadLine(),
                    RecordsNumber = int.Parse(reader.ReadLine()),
                    Command = reader.ReadLine(),
                    OutFile = reader.ReadLine(),
                    Format = DataFormat.Parse(reader.ReadLine()),
                    Portal = bool.Parse(reader.ReadLine()),
                    Link = reader.ReadLine()
                };
            }
        }
    }
}